package org.jeecg.modules.demo.xxljob;/**
 * /**
 *
 * @Description:TODO
 * @author:yxx
 * @date:2022年10月2022/10/31日19:10
 */

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.ch.Utils.DateUtil;
import org.jeecg.modules.demo.ch.common.CommonMst;
import org.jeecg.modules.demo.ch.entity.ChDailyRecord;
import org.jeecg.modules.demo.ch.entity.ChDailyRecordDetails;
import org.jeecg.modules.demo.ch.entity.ChWorkPlanForNextWeek;
import org.jeecg.modules.demo.ch.service.IChDailyRecordDetailsService;
import org.jeecg.modules.demo.ch.service.IChDailyRecordService;
import org.jeecg.modules.demo.ch.service.IChWorkPlanForNextWeekService;
import org.jeecg.modules.demo.ch.service.IWeeklyReportFeedbackService;
import org.jeecg.modules.demo.ch.vo.ChDailyRecordPage;
import org.jeecg.modules.message.handle.impl.EmailSendMsgHandle;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * xxl-job定时任务测试
 */
@Component
@Slf4j
public class DailyRecordJobHandler {

    @Autowired
    private EmailSendMsgHandle emailSendMsgHandle;

    @Value("${jeecg.path.download}")
    private String download;

    @Value("${jeecg.path.template}")
    private String template;

    private Boolean isSendAttachment;//是否发送附件

    @Autowired
    private IWeeklyReportFeedbackService weeklyReportFeedbackService;

    @Autowired
    private IChDailyRecordService iChDailyRecordService;

    @Autowired
    private IChDailyRecordDetailsService iChDailyRecordDetailsService;

    @Autowired
    private IChWorkPlanForNextWeekService iChWorkPlanForNextWeekService;

    @Lazy
    @Autowired
    private CommonAPI commonApi;

    /**
     * 简单任务
     * 每天的日报形成周报并发送邮件
     * @param params
     * @return
     */
    @XxlJob(value = "DailyRecordSendEmail")
    public ReturnT<String> DailyRecordSendEmail(String params) {
        //获取IT部所有的成员.
        List<LoginUser> loginUsers = commonApi.getUserByDeptId(CommonMst.DAILY_RECORD_SYSTEM.IT_DEPT_ID);
        if (CollectionUtils.isEmpty(loginUsers)){
            throw new RuntimeException("IT部无员工信息!");
        }
        for (LoginUser loginUser : loginUsers) {
            String realname = loginUser.getRealname();//真实姓名
            if (StringUtils.hasLength(realname)){
                //给单个人发送邮箱 邮件
                sendEmailForSingle(realname);
            }
        }
        return ReturnT.SUCCESS;
    }

    /**
     * 给单个人发送邮箱 邮件
     * @param realname
     */
    public void sendEmailForSingle(String realname){
        //用来给模板赋值
        HashMap<String, Object> hashMap = new HashMap<>();
        //查询数据
        hashMap = getProData(hashMap, realname);

//        String es_receiver="guyu@sz-changhong.com";
//        String es_title ="周报未完成情况";
        String es_title =realname+"的工作周报";
        String es_content = "";
        if (hashMap.isEmpty()) {
            return;
        } else {
            es_content = CommonMst.DAILY_RECORD_SYSTEM.EMAIL_FORMAT2;
            isSendAttachment = true; //发送邮件
            //导出excel
            exportExcel(es_title, hashMap);
        }
        //发送邮件
        //生成数据并发送邮箱
        String jobParam = XxlJobHelper.getJobParam();
        Map<String, Object> map = (Map<String, Object>) JSON.parse(jobParam);
        String emailReceivers = (String) map.get("emailReceiver");
        XxlJobHelper.log("jeecgBoot自定义的expirationSendEmail传入的emailReceivers{}", emailReceivers);

        if (emailReceivers.contains(",")) {
            String[] emailReceiver = emailReceivers.split(",");
            for (String emailAddress : emailReceiver) {
                emailSendMsgHandle.sendMsg(emailAddress, es_title, es_content, isSendAttachment);
            }
        } else {
            emailSendMsgHandle.sendMsg(emailReceivers, es_title, es_content, isSendAttachment);
        }
    }

    /**
     * 导出excel
     */
    public void exportExcel(String es_title, HashMap<String, Object> hashMap) {
        //1.构建需要导出的数据
        //2.存放导出的数据
        hashMap.put("title", es_title);
        TemplateExportParams params = getTemplateParams(CommonMst.DAILY_RECORD_SYSTEM.TEMPLATE_NAME);
        Workbook workbook = ExcelExportUtil.exportExcel(params, hashMap);

        File savefile = new File(download);
        if (!savefile.exists()) {
            savefile.mkdirs();
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(download + es_title + ".xlsx");
            workbook.write(fos);
            fos.close();
        } catch (FileNotFoundException e) {
            log.error("exportExcel FileNotFoundException异常", e);
            e.printStackTrace();
        } catch (IOException e) {
            log.error("exportExcel IOException异常", e);
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    log.error("exportExcel IOException异常", e);
                    e.printStackTrace();
                }
            }
        }
    }



    /**
     * 查询数据
     * @param hashMap
     * @param realname 真实姓名
     * @return
     */
    public  HashMap<String, Object>  getProData(HashMap<String, Object> hashMap,String realname) {
        //周报内容初始赋值
        hashMap.put("Monday","");
        hashMap.put("Tuesday","");
        hashMap.put("Wednesdayday","");
        hashMap.put("Thursday","");
        hashMap.put("Friday","");
        hashMap.put("Saturday","");
        hashMap.put("Sunday","");
        //本周重点工作初始赋值
        hashMap.put("lastWeekPlayContent","");//上周工作计划
        hashMap.put("ratio","");//完成比例（通过计算 本周未完成的数占总条数的概率）
        hashMap.put("execution","");//完成情况（全部完成就写已完成，比例只要不是100%就写进行中）

        SimpleDateFormat sf=new SimpleDateFormat(CommonMst.WEEKLYREPORT.DATEFORMAT);
        String beginTime = sf.format(DateUtil.getThisWeek().get("monday"));//本周一
        String endTime = sf.format(DateUtil.getThisWeek().get("sunday"));//本周日
        SimpleDateFormat sf2=new SimpleDateFormat(CommonMst.WEEKLYREPORT.DATEFORMAT2);
        String beginTime2 = sf2.format(DateUtil.getThisWeek().get("monday"));//本周一
        String endTime2 = sf2.format(DateUtil.getThisWeek().get("sunday"));//本周日

        hashMap.put("userName",realname);//姓名
        hashMap.put("beginTime",beginTime2);//开始日期
        hashMap.put("endTime",endTime2);//结束日期
        //默认查询本周的日报数据
        //结束日期+1天
        LocalDate date = LocalDate.parse(endTime);
        LocalDate localDate = date.plusDays(1);
        DateTimeFormatter df = DateTimeFormatter.ofPattern(CommonMst.WEEKLYREPORT.DATEFORMAT);
        endTime = localDate.format(df);
        LambdaQueryWrapper<ChDailyRecord> chDailyRecordLambdaQueryWrapper = new QueryWrapper<ChDailyRecord>().lambda()
                .ge(ChDailyRecord::getCreateTime, beginTime)
                .le(ChDailyRecord::getCreateTime, endTime)
                .eq(ChDailyRecord::getName,realname);
        List<ChDailyRecord> chDailyRecordList = iChDailyRecordService.list(chDailyRecordLambdaQueryWrapper);
        if (CollectionUtils.isEmpty(chDailyRecordList)){
            return new HashMap<>();
        }
        ArrayList<ChDailyRecordPage> pageList = new ArrayList<>();
        for (ChDailyRecord main : chDailyRecordList) {
            hashMap.put("littleTitle",main.getTitle());//标题
            ChDailyRecordPage vo = new ChDailyRecordPage();
            BeanUtils.copyProperties(main, vo);
            String dayOfWeek = main.getDayOfWeek();//星期几
            List<ChDailyRecordDetails> chDailyRecordDetailsList = iChDailyRecordDetailsService.selectByMainId(main.getId());
            vo.setChDailyRecordDetailsList(chDailyRecordDetailsList);
            if (!CollectionUtils.isEmpty(chDailyRecordDetailsList)){
                //生成周报内容 放在hashMap中
                generateWeeklyRportContent(chDailyRecordDetailsList,hashMap,dayOfWeek);
            }
            pageList.add(vo);
        }
        //获取上周重点工作计划 (默认查询上一周的)
        //获取上周一和周日
        String lastMonday = sf.format(DateUtil.getLastWeek().get("monday"));//上周一
        String lastSunday = sf.format(DateUtil.getLastWeek().get("sunday"));//上周日
        //结束日期+1天
         lastSunday = LocalDate.parse(lastSunday).plusDays(1).format(df);
        LambdaQueryWrapper<ChWorkPlanForNextWeek> lastWeekLambdaQueryWrapper = new QueryWrapper<ChWorkPlanForNextWeek>().lambda()
                .eq(ChWorkPlanForNextWeek::getName, realname)
                .ge(ChWorkPlanForNextWeek::getCreateTime, lastMonday)
                .le(ChWorkPlanForNextWeek::getCreateTime, lastSunday)
                .orderByDesc(ChWorkPlanForNextWeek::getName)
                .orderByDesc(ChWorkPlanForNextWeek::getCreateTime);
        List<ChWorkPlanForNextWeek> chWorkPlanForLastWeekList = iChWorkPlanForNextWeekService.list(lastWeekLambdaQueryWrapper);
        // 将上周计划的所有项  放在一起
        if (!CollectionUtils.isEmpty(chWorkPlanForLastWeekList)){
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < chWorkPlanForLastWeekList.size(); i++) {
                String prefix = getPrefix(i+1);
                String keyWorkPlan = chWorkPlanForLastWeekList.get(i).getKeyWorkPlan();
                sb.append(prefix).append(keyWorkPlan).append(CommonMst.DAILY_RECORD_SYSTEM.Tab);
            }
            hashMap.put("lastWeekPlayContent",sb.toString());//上周工作计划
        }
        //存放本周完成率以及完成情况
        saveComplateRatioAndStatus(hashMap,realname,beginTime,endTime);
        //获取下周重点工作计划 (默认查询获取本周一和周日)
        LambdaQueryWrapper<ChWorkPlanForNextWeek> nextWeekLambdaQueryWrapper = new QueryWrapper<ChWorkPlanForNextWeek>().lambda()
                .eq(ChWorkPlanForNextWeek::getName, realname)
                .ge(ChWorkPlanForNextWeek::getCreateTime, beginTime)
                .le(ChWorkPlanForNextWeek::getCreateTime, endTime)
                .orderByDesc(ChWorkPlanForNextWeek::getName)
                .orderByDesc(ChWorkPlanForNextWeek::getCreateTime);
        List<ChWorkPlanForNextWeek> chWorkPlanForNextWeekList = iChWorkPlanForNextWeekService.list(nextWeekLambdaQueryWrapper);
        List<Map<String, Object>> listMap2 = new ArrayList<Map<String, Object>>();
        if (CollectionUtils.isEmpty(chWorkPlanForNextWeekList)){
            hashMap.put("maplist2",listMap2);
        }else {
            for (int i = 0; i<chWorkPlanForNextWeekList.size();i++){
                HashMap<String, Object> hashMap2 = new HashMap<>();
                hashMap2.put("number",getPrefix(i+1));
                hashMap2.put("title",chWorkPlanForNextWeekList.get(i).getTitle());
                hashMap2.put("keyWorkPlan",chWorkPlanForNextWeekList.get(i).getKeyWorkPlan());
                hashMap2.put("keyPoints",chWorkPlanForNextWeekList.get(i).getKeyPoints());
                listMap2.add(hashMap2);
            }
            hashMap.put("maplist2",listMap2);
        }
        return hashMap;
    }

    /**
     * 存放本周完成率以及完成情况
     * @param hashMap
     * @param realName
     * @param beginTime
     * @param endTime
     */
    public void saveComplateRatioAndStatus(HashMap<String, Object> hashMap,String realName,String beginTime,String endTime){
        //通过姓名获取本周所有的工作项
         int total = 0;
         int complateNum = 0;
         String execution ="";
        List<ChDailyRecordDetails> notCompleteList = new ArrayList<>();
       List<ChDailyRecordDetails> chDailyRecordDetailsList =  iChDailyRecordDetailsService.getThisWeekAllItemByName(realName,beginTime,endTime);
       if (!CollectionUtils.isEmpty(chDailyRecordDetailsList)){
            total = chDailyRecordDetailsList.size();
            //状态已完成的所有列表
           List<ChDailyRecordDetails> completeList = chDailyRecordDetailsList.stream().filter(p -> p.getStatus().equals(CommonMst.DAILY_RECORD_SYSTEM.STATUS1)).collect(Collectors.toList());
           //状态未完成的所有列表
           notCompleteList = chDailyRecordDetailsList.stream().filter(p -> !p.getStatus().equals(CommonMst.DAILY_RECORD_SYSTEM.STATUS1)).collect(Collectors.toList());
           complateNum = completeList.size();
       }
       if (total != 0){
           DecimalFormat df =new DecimalFormat();
           df.setMaximumFractionDigits(2);
           df.setMinimumFractionDigits(2);
           String orderRate = df.format(complateNum *100.00 / total) +"%";
           hashMap.put("ratio",orderRate);//完成比例（通过计算 本周未完成的数占总条数的概率）
       }
       //存放完成情况
        if (CollectionUtils.isEmpty(notCompleteList)){
            hashMap.put("execution","全部已完成");//完成情况（全部完成就写已完成，比例只要不是100%就写进行中）
        }else {
            StringBuilder sb = new StringBuilder("本周未完成进度情况如下:");
            for (int i = 0; i < notCompleteList.size(); i++) {
                String prefix = getPrefix(i+1);
                String toDoList = notCompleteList.get(i).getToDoList();
                Integer completeRatio = notCompleteList.get(i).getCompleteRatio();
                sb.append(CommonMst.DAILY_RECORD_SYSTEM.Tab).append(prefix).append(toDoList).append(CommonMst.DAILY_RECORD_SYSTEM.STATUS1).append(completeRatio).append(CommonMst.DAILY_RECORD_SYSTEM.PERCEBT_SIGN).append(CommonMst.DAILY_RECORD_SYSTEM.Tab);
                execution=sb.toString();
            }
            hashMap.put("execution",execution);//完成情况（全部完成就写已完成，比例只要不是100%就写进行中）
        }

    }

    /**
     * 生成周报内容 放在hashMap中
     * @param chDailyRecordDetailsList
     * @param hashMap
     */
    public void generateWeeklyRportContent(List<ChDailyRecordDetails> chDailyRecordDetailsList,HashMap<String, Object> hashMap,String dayOfWeek){
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < chDailyRecordDetailsList.size(); i++) {
            String prefix = getPrefix(i+1);
            String toDoList = chDailyRecordDetailsList.get(i).getToDoList();
            sb.append(prefix).append(toDoList).append(CommonMst.DAILY_RECORD_SYSTEM.Tab);
        }
        String content = sb.toString();//一天的内容
        if (dayOfWeek.equals(CommonMst.DAILY_RECORD_SYSTEM.MONDAY)){
            hashMap.put("Monday",content);
        }else if (dayOfWeek.equals(CommonMst.DAILY_RECORD_SYSTEM.TUESDAY)){
            hashMap.put("Tuesday",content);
        }else if (dayOfWeek.equals(CommonMst.DAILY_RECORD_SYSTEM.WEDNESDAY)){
            hashMap.put("Wednesdayday",content);
        }else if (dayOfWeek.equals(CommonMst.DAILY_RECORD_SYSTEM.THURSDAY)){
            hashMap.put("Thursday",content);
        }else if (dayOfWeek.equals(CommonMst.DAILY_RECORD_SYSTEM.FRIDAY)){
            hashMap.put("Friday",content);
        }else if (dayOfWeek.equals(CommonMst.DAILY_RECORD_SYSTEM.SATURDAY)){
            hashMap.put("Saturday",content);
        }else if (dayOfWeek.equals(CommonMst.DAILY_RECORD_SYSTEM.SUNDAY)){
            hashMap.put("Sunday",content);
        }
    }

    /**
     * 获取前缀
     * @param i
     * @return
     */
    public String getPrefix(int i){
        String prefix;
        if (i==1){
            prefix = CommonMst.DAILY_RECORD_SYSTEM.ONE;
        }else if (i==2){
            prefix = CommonMst.DAILY_RECORD_SYSTEM.TWO;
        }else if (i==3){
            prefix = CommonMst.DAILY_RECORD_SYSTEM.THREE;
        }else if (i==4){
            prefix = CommonMst.DAILY_RECORD_SYSTEM.FOUR;
        }else if (i==5){
            prefix = CommonMst.DAILY_RECORD_SYSTEM.FIVE;
        }else if (i==6){
            prefix = CommonMst.DAILY_RECORD_SYSTEM.SIX;
        }else if (i==7){
            prefix = CommonMst.DAILY_RECORD_SYSTEM.SEVEN;
        }else if (i==8){
            prefix = CommonMst.DAILY_RECORD_SYSTEM.EIGHT;
        }else if (i==9){
            prefix = CommonMst.DAILY_RECORD_SYSTEM.NINE;
        }else if (i==10){
            prefix = CommonMst.DAILY_RECORD_SYSTEM.TEN;
        }else{
            prefix = CommonMst.DAILY_RECORD_SYSTEM.OTHER;
        }
        return prefix;
    }


//    //查询数据（TODO）
//    public static List<WeeklyReportFeedback> getProData(IWeeklyReportFeedbackService weeklyReportFeedbackService) {
//        SimpleDateFormat sf=new SimpleDateFormat(CommonMst.WEEKLYREPORT.DATEFORMAT);
//        String beginTime = sf.format(DateUtil.getLastWeek().get("monday"));//上周一
//        String endTime = sf.format(DateUtil.getLastWeek().get("sunday"));//上周日
//        //默认查询上一周的
//        //结束日期+1天
//        LocalDate date = LocalDate.parse(endTime);
//        LocalDate localDate = date.plusDays(1);
//        DateTimeFormatter df = DateTimeFormatter.ofPattern(CommonMst.WEEKLYREPORT.DATEFORMAT);
//        endTime = localDate.format(df);
//        return weeklyReportFeedbackService.selectChWeeklyReportFeedbackListForLastWeek(beginTime,endTime);
//    }

    /**
     * 返回导出参数对象
     *
     * @param name
     * @return
     */
    public TemplateExportParams getTemplateParams(String name) {
        return new TemplateExportParams(template + name);
    }


}

